﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Casamiel.API.Application;
using Casamiel.API.Application.Models.Store;
using Casamiel.API.Infrastructure;
using Casamiel.API.Infrastructure.Filters;
using Casamiel.Application.Commands.GroupPurchase;
using Casamiel.Common;
using Casamiel.Common.Extensions;
using Casamiel.Domain.Entity;
using Casamiel.Domain.Request.GroupPurchase;
using Casamiel.Domain.Response;
using Casamiel.Domain.Response.GroupPurchase;
using Enyim.Caching;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Casamiel.API.Controllers.V1.GroupPurchase
{
    /// <summary>
    /// 
    /// </summary>
    [ApiVersion("1.0")]
    [Route("api/v{api-version:apiVersion}/GroupPurchase/[controller]")]
    [ApiController]
    [EnableCors("any")]
    [Authorize]
    [TypeFilterAttribute(typeof(CheckTokenAttribute))]
    public class OrderController : BaseController
    {
        private readonly NLog.ILogger logger = NLog.LogManager.GetLogger("OrderService");
        private readonly IMediator _mediator;
        private readonly IMemcachedClient _memcachedClient;
        //private readonly string _memcachedPrex;
        private readonly IRefundService _refundService;
        private readonly IStoreApiService _storeApiService;



        /// <summary>
        /// 
        /// </summary>
        /// <param name="mediator"></param>
        /// <param name="memcachedClient"></param>
        /// <param name="refundService"></param>
        /// <param name="storeApiService"></param>
        public OrderController(IMediator mediator, IMemcachedClient memcachedClient, IRefundService refundService, IStoreApiService storeApiService)
        {
            _mediator = mediator;
            _memcachedClient = memcachedClient;
            _refundService = refundService;
            _storeApiService = storeApiService;
        }


        /// <summary>
        /// 创建团购订单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<PaymentRsp>> CreateOrder(CreateGroupPurchaseOrderRequest request, [FromHeader(Name = "u-token")] string token)
        {
            if (request == null) {
                throw new ArgumentNullException(nameof(request));
            }

            if (string.IsNullOrEmpty(token)) {
                throw new ArgumentException("message", nameof(token));
            }

            var cmd = new CreateOrderCommand( LoginInfo.Item3) {
                Mobile = base.Mobile,
                GrouponId = request.GrouponId,
                OrderType = request.OrderType,
                LeaderCode = request.LeaderCode,
                Paymethod = request.Paymethod,
                Quantity = request.Quantity,
                Remark = request.Remark,
                HeadImgurl = request.HeadImgurl,
                InvoiceId = request.InvoiceId
            };
            var result = await _mediator.Send(cmd).ConfigureAwait(false);


            logger.Trace($"req:{JsonConvert.SerializeObject(cmd)},{JsonConvert.SerializeObject(result)}");
           // if (result.Code == 0 && result.Content.Payed != true) {
                //    logger.Trace($"{JsonConvert.SerializeObject(result.Content)}");
                // var array = result.Content.Paymentrequest.Split(',');
                if (result.Code != 0) {
                return new BaseResult<PaymentRsp>(null, result.Code, result.Msg);
            }
            var p_tradeno = $"C{DateTime.Now.ToString("yyMMddHHmmssfff", CultureInfo.CurrentCulture)}";
            var payment = new PaymentRecord {
                ShopName = "",
                OperationMethod = (int)OperationMethod.GroupPurchase,
                TradeNo = p_tradeno,
                Amount = result.Content.PayMoney.ToString().ToDouble(0),
                PayMethod = request.Paymethod,
                BillNO = result.Content.OrderCode,
                State = 0,
                OperationState = 0,
                CreateTime = DateTime.Now,
                Mobile = base.Mobile
            };

            var command = new Application.Commands.CreatePaymentRequestCommand(payment, request.Id, PaymentScenario.GroupPurchase);
            var result1 = await _mediator.Send(command).ConfigureAwait(false);

            var pay = new PaymentRsp {
                OrderCode = result1.Ordercode,
                Payed = result1.Payed,
                Paymentrequest = result1.Paymentrequest,
                PayMethod = result1.PayMethod.ToInt32(0)
            };
            return new BaseResult<PaymentRsp>(pay, 0, "");

        }

        /// <summary>
        /// 参与拼团页面详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<JoinGroupPurchseOrderResponse>> GetJoinGroupPurchaseOrderDetail(GetOrderDetailRequest request)
        {

            if (request == null) {
                throw new ArgumentNullException(nameof(request));
            }

            var cmd = new JoinGroupPurchaseOrderDetailCommand(request.OrderCode, LoginInfo.Item3);
            var rsp = await _mediator.Send(cmd).ConfigureAwait(false);
            return rsp;
        }

        /// <summary>
        /// 订单详情
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<GroupPurchaseOrderDetailResponse>> GetDetail(GetOrderDetailRequest request, [FromHeader(Name = "u-token")] string token)
        {
            if (request == null) {
                throw new ArgumentNullException(nameof(request));
            }

            if (string.IsNullOrEmpty(token)) {
                throw new ArgumentException("message", nameof(token));
            }

            var cmd = new GetOrderDetailCommand(request.OrderCode, base.Mobile, LoginInfo.Item3);
            var rsp = await _mediator.Send(cmd).ConfigureAwait(false);
            return rsp;
        }

        /// <summary>
        /// 去支付
        /// </summary>
        /// <param name="request"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<BaseResult<PaymentRsp>> Payment([FromBody] GroupPurchasePaymentRequest request, [FromHeader(Name = "u-token")]string token)
        {
            if (request == null) {
                throw new ArgumentNullException(nameof(request));
            }

            if (string.IsNullOrEmpty(token)) {
                throw new ArgumentException("message", nameof(token));
            }
            var cmd = new GetOrderDetailCommand(request.OrderCode, base.Mobile,LoginInfo.Item3);
            var result = await _mediator.Send(cmd).ConfigureAwait(false);
            if (result.Code != 0) {
                return new BaseResult<PaymentRsp>(null, result.Code, result.Msg);
            }
            if (result.Content.OrderStatus != 0) {
                return new BaseResult<PaymentRsp>(null, 999, "不是待支付订单");
            }
            var p_tradeno = $"C{DateTime.Now.ToString("yyMMddHHmmssfff", CultureInfo.CurrentCulture)}";
            var payment = new PaymentRecord {
                ShopName = "",
                OperationMethod = (int)OperationMethod.GroupPurchase,
                TradeNo = p_tradeno,
                Amount = result.Content.PayMoney.ToString().ToDouble(0),
                PayMethod = request.Paymethod,
                BillNO = result.Content.OrderCode,
                State = 0,
                OperationState = 0,
                CreateTime = DateTime.Now,
                Mobile = base.Mobile
            };

            var command = new Application.Commands.CreatePaymentRequestCommand(payment, request.Id, PaymentScenario.GroupPurchase);
            var result1 = await _mediator.Send(command).ConfigureAwait(false);

            var pay = new PaymentRsp {
                OrderCode = result1.Ordercode,
                Payed = result1.Payed,
                Paymentrequest = result1.Paymentrequest,
                PayMethod = result1.PayMethod.ToInt32(0)
            };
            return new BaseResult<PaymentRsp>(pay, 0, "");
        }

        /// <summary>
        /// 我的订单列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<PagingResultRsp<List<GrouponPurchaseOrderResponse>>> GetMyOrderList(MyOrderListRequest request, [FromHeader(Name = "u-token")]string token)
        {
            if (request == null) {
                throw new ArgumentNullException(nameof(request));
            }

            if (string.IsNullOrEmpty(token)) {
                throw new ArgumentException("message", nameof(token));
            }

            var cmd = new MyOrderListCommand( LoginInfo.Item3)
            {
                Mobile = base.Mobile,
                PageIndex = request.PageIndex,
                PageSize = request.PageSize
            };

            return await _mediator.Send(cmd).ConfigureAwait(false);
        }

        /// <summary>
        ///   取消订单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        [TypeFilterAttribute(typeof(CheckTokenAttribute))]
        public async Task<ActionResult<BaseResult<string>>> CancelOrder([FromBody] GetOrderDetailRequest request, [FromHeader(Name = "u-token")]  string token)
        {
            if (request == null) {
                throw new ArgumentNullException(nameof(request));
            }
            logger.Trace($"{JsonConvert.SerializeObject(request)}");
            var mobile = MemberHelper.GetMobile(token);

            var cmd = new GetOrderDetailCommand(request.OrderCode, base.Mobile, LoginInfo.Item3);
            var rsp = await _mediator.Send(cmd).ConfigureAwait(false);
            GroupPurchaseOrderDetailResponse entity = rsp.Content;


            if (entity != null) {
                if (entity.OrderStatus == 4) {
                     var m = await _refundService.GroupPurchaseOrderRefund(request.OrderCode).ConfigureAwait(false);
                    if (m.code == 0) {

                        var rsp1 = await _storeApiService.ChangeGrouponOrderStatusAsync(request.OrderCode, mobile, 6, 0).ConfigureAwait(false);
                        logger.Trace($"{JsonConvert.SerializeObject(rsp1)}");
                        //await _order.OrderOperationLogAddAsync<ICasaMielSession>(new OrderOperationLog {
                        //    BillType = 2, CreateTime = DateTime.Now, Remark = "用户发起订单取消成功",
                        //    OrderBaseId = entity.OrderBaseId, OrderCode = entity.OrderCode
                        //}).ConfigureAwait(false);
                    }
                    return Ok(m);
                } else {
                    return Ok(new { code = 9999, msg = "订单状态不是已完成不能取消" });
                }
            } else {
                return Ok(new { code = 9999, msg = "订单不存在！" });

            }

        }

    }
}